package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;

import com.ruoyi.system.domain.SysDataset;
import com.ruoyi.system.domain.SysDatasetVersion;
import com.ruoyi.system.domain.vo.SysDatasetQuery;
import com.ruoyi.system.service.ISysDatasetService;

import io.swagger.annotations.*;

/**
 * 数据集配置Controller
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/dataset")
@Api(tags = "数据集管理")
public class SysDatasetController extends BaseController
{
    private String prefix = "system/dataset";

    @Autowired
    private ISysDatasetService datasetService;

    /**
     * 进入数据集管理页面
     */
    @PreAuthorize("@ss.hasPermi('system:dataset:view')")
    @GetMapping()
    public String dataset()
    {
        return prefix + "/dataset";
    }

    /**
     * 查询数据集配置列表
     */
    @ApiOperation("查询数据集列表")
    @PreAuthorize("@ss.hasPermi('system:dataset:list')")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestBody SysDatasetQuery query)
    {
        startPage();
        List<SysDataset> list = datasetService.selectDatasetList(query);
        return getDataTable(list);
    }

    /**
     * 导出数据集配置列表
     */
    @ApiOperation("导出数据集列表")
    @PreAuthorize("@ss.hasPermi('system:dataset:export')")
    @Log(title = "数据集配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(@RequestBody SysDatasetQuery query)
    {
        List<SysDataset> list = datasetService.selectDatasetList(query);
        ExcelUtil<SysDataset> util = new ExcelUtil<SysDataset>(SysDataset.class);
        return util.exportExcel(list, "数据集配置");
    }

    /**
     * 新增数据集配置页面
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存数据集配置
     */
    @ApiOperation("新增数据集")
    @PreAuthorize("@ss.hasPermi('system:dataset:add')")
    @Log(title = "数据集配置", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated @RequestBody SysDataset dataset)
    {
        if (Constants.NOT_UNIQUE.equals(datasetService.checkDatasetCodeUnique(dataset)))
        {
            return AjaxResult.error("新增数据集失败，数据集编码已存在");
        }
        return toAjax(datasetService.insertDataset(dataset));
    }

    /**
     * 修改数据集配置页面
     */
    @GetMapping("/edit/{datasetId}")
    public String edit(@PathVariable("datasetId") Long datasetId, ModelMap mmap)
    {
        mmap.put("dataset", datasetService.selectDatasetById(datasetId));
        return prefix + "/edit";
    }

    /**
     * 修改保存数据集配置
     */
    @ApiOperation("修改数据集")
    @PreAuthorize("@ss.hasPermi('system:dataset:edit')")
    @Log(title = "数据集配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated @RequestBody SysDataset dataset)
    {

        return toAjax(datasetService.updateDataset(dataset));
    }

    /**
     * 删除数据集配置
     */
    @ApiOperation("删除数据集")
    @PreAuthorize("@ss.hasPermi('system:dataset:remove')")
    @Log(title = "数据集配置", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        String[] idArray = StringUtils.split(ids, ",");
        Long[] datasetIds = new Long[idArray.length];
        for (int i = 0; i < idArray.length; i++) {
            datasetIds[i] = Long.valueOf(idArray[i]);
        }
        return toAjax(datasetService.deleteDatasetByIds(datasetIds));
    }

    /**
     * 校验数据集编码
     */
    @ApiOperation("校验数据集编码唯一性")
    @PostMapping("/checkDatasetCodeUnique")
    @ResponseBody
    public String checkDatasetCodeUnique(SysDataset dataset)
    {
        return datasetService.checkDatasetCodeUnique(dataset);
    }

    /**
     * 测试数据集连接
     */
    @ApiOperation("测试数据集连接")
    @PostMapping("/testConnection")
    @ResponseBody
    public AjaxResult testConnection(@RequestBody SysDataset dataset)
    {
        try
        {
            Map<String, Object> result = datasetService.testDatasetConnection(dataset);
            if ((boolean) result.get("success"))
            {
                return AjaxResult.success("测试成功", result);
            }
            else
            {
                return AjaxResult.error((String) result.get("message"));
            }
        }
        catch (Exception e)
        {
            return AjaxResult.error("测试失败: " + e.getMessage());
        }
    }

    /**
     * 预览数据集数据
     */
    @ApiOperation("预览数据集数据")
    @PostMapping("/previewData/{datasetId}")
    @ResponseBody
    public AjaxResult previewData(@PathVariable("datasetId") Long datasetId, @RequestBody Map<String, Object> params, Integer limit)
    {
        try
        {
            List<Map<String, Object>> data = datasetService.previewDatasetData(datasetId, params, limit);
            return AjaxResult.success(data);
        }
        catch (Exception e)
        {
            return AjaxResult.error("预览失败: " + e.getMessage());
        }
    }

    /**
     * 执行数据集查询
     */
    @ApiOperation("执行数据集查询")
    @PostMapping("/executeQuery/{datasetId}")
    @ResponseBody
    public AjaxResult executeQuery(@PathVariable("datasetId") Long datasetId, @RequestBody Map<String, Object> params, Integer pageNum, Integer pageSize)
    {
        try
        {
            Map<String, Object> result = datasetService.executeDatasetQuery(datasetId, params, pageNum, pageSize);
            return AjaxResult.success(result);
        }
        catch (Exception e)
        {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 更新数据集元数据
     */
    @ApiOperation("更新数据集元数据")
    @PostMapping("/updateMetadata/{datasetId}")
    @ResponseBody
    public AjaxResult updateMetadata(@PathVariable("datasetId") Long datasetId)
    {
        boolean success = datasetService.updateDatasetMetadata(datasetId);
        if (success)
        {
            return AjaxResult.success("更新元数据成功");
        }
        else
        {
            return AjaxResult.error("更新元数据失败");
        }
    }

    /**
     * 刷新数据集数据量
     */
    @ApiOperation("刷新数据集数据量")
    @PostMapping("/refreshCount/{datasetId}")
    @ResponseBody
    public AjaxResult refreshCount(@PathVariable("datasetId") Long datasetId)
    {
        try
        {
            Long count = datasetService.refreshDatasetCount(datasetId);
            return AjaxResult.success("刷新成功", count);
        }
        catch (Exception e)
        {
            return AjaxResult.error("刷新失败: " + e.getMessage());
        }
    }

    /**
     * 批量刷新数据集
     */
    @ApiOperation("批量刷新数据集")
    @PostMapping("/refreshBatch")
    @ResponseBody
    public AjaxResult refreshBatch(String ids)
    {
        try
        {
            String[] idArray = StringUtils.split(ids, ",");
            Long[] datasetIds = new Long[idArray.length];
            for (int i = 0; i < idArray.length; i++) {
                datasetIds[i] = Long.valueOf(idArray[i]);
            }
            int successCount = 0;
            int errorCount = 0;
            
            for (Long datasetId : datasetIds)
            {
                boolean success = datasetService.updateDatasetMetadata(datasetId);
                if (success)
                {
                    successCount++;
                }
                else
                {
                    errorCount++;
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("successCount", successCount);
            result.put("errorCount", errorCount);
            
            return AjaxResult.success("刷新完成", result);
        }
        catch (Exception e)
        {
            return AjaxResult.error("批量刷新失败: " + e.getMessage());
        }
    }

    /**
     * 切换数据集状态
     */
    @ApiOperation("切换数据集状态")
    @PreAuthorize("@ss.hasPermi('system:dataset:edit')")
    @Log(title = "数据集配置", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(@RequestBody SysDataset dataset)
    {
        SysDataset oldDataset = datasetService.selectDatasetById(dataset.getDatasetId());
        oldDataset.setStatus(dataset.getStatus());
        return toAjax(datasetService.updateDataset(oldDataset));
    }

    /**
     * 根据数据源ID查询数据集列表
     */
    @ApiOperation("根据数据源ID查询数据集列表")
    @PostMapping("/byDatasource/{datasourceId}")
    @ResponseBody
    public AjaxResult getByDatasourceId(@PathVariable("datasourceId") String datasourceId)
    {
        List<SysDataset> datasets = datasetService.selectDatasetByDatasourceId(datasourceId);
        return AjaxResult.success(datasets);
    }

    /**
     * 获取所有启用的数据集
     */
    @ApiOperation("获取所有启用的数据集")
    @GetMapping("/enabledList")
    @ResponseBody
    public AjaxResult getEnabledDatasets()
    {
        List<SysDataset> datasets = datasetService.selectEnabledDataset();
        return AjaxResult.success(datasets);
    }
    
    /**
     * 获取数据集类型列表
     */
    @ApiOperation("获取数据集类型列表")
    @GetMapping("/getDatasetTypeList")
    @ResponseBody
    public AjaxResult getDatasetTypeList()
    {
        // 数据集类型列表
        List<Map<String, String>> typeList = new ArrayList<>();
        Map<String, String> tableType = new HashMap<>();
        tableType.put("value", "table");
        tableType.put("label", "表");
        typeList.add(tableType);
        
        Map<String, String> viewType = new HashMap<>();
        viewType.put("value", "view");
        viewType.put("label", "视图");
        typeList.add(viewType);
        
        Map<String, String> queryType = new HashMap<>();
        queryType.put("value", "query");
        queryType.put("label", "自定义查询");
        typeList.add(queryType);
        
        return AjaxResult.success(typeList);
    }

    /**
     * 获取数据集版本管理页面
     */
    @GetMapping("/version/{datasetId}")
    public String version(@PathVariable("datasetId") Long datasetId, ModelMap mmap)
    {
        mmap.put("datasetId", datasetId);
        mmap.put("dataset", datasetService.selectDatasetById(datasetId));
        return prefix + "/version";
    }

    /**
     * 获取数据集版本历史
     */
    @ApiOperation("获取数据集版本历史")
    @PostMapping("/version/list/{datasetId}")
    @ResponseBody
    public TableDataInfo versionList(@PathVariable("datasetId") Long datasetId)
    {
        startPage();
        List<SysDatasetVersion> versions = datasetService.selectDatasetVersionList(datasetId);
        return getDataTable(versions);
    }

    /**
     * 创建新版本
     */
    @ApiOperation("创建新版本")
    @PreAuthorize("@ss.hasPermi('system:dataset:edit')")
    @Log(title = "数据集版本", businessType = BusinessType.INSERT)
    @PostMapping("/version/create")
    @ResponseBody
    public AjaxResult createVersion(Long datasetId, String changeDescription)
    {
        try
        {
            SysDataset dataset = datasetService.selectDatasetById(datasetId);
            if (dataset == null)
            {
                return AjaxResult.error("数据集不存在");
            }
            String version = datasetService.createNewVersion(dataset, changeDescription);
            return AjaxResult.success("创建版本成功", version);
        }
        catch (Exception e)
        {
            return AjaxResult.error("创建版本失败: " + e.getMessage());
        }
    }

    /**
     * 回滚到指定版本
     */
    @ApiOperation("回滚到指定版本")
    @PreAuthorize("@ss.hasPermi('system:dataset:edit')")
    @Log(title = "数据集版本", businessType = BusinessType.UPDATE)
    @PostMapping("/version/rollback/{versionId}")
    @ResponseBody
    public AjaxResult rollbackVersion(@PathVariable("versionId") Long versionId)
    {
        boolean success = datasetService.rollbackToVersion(versionId);
        if (success)
        {
            return AjaxResult.success("版本回滚成功");
        }
        else
        {
            return AjaxResult.error("版本回滚失败");
        }
    }

    /**
     * 删除版本
     */
    @ApiOperation("删除版本")
    @PreAuthorize("@ss.hasPermi('system:dataset:edit')")
    @Log(title = "数据集版本", businessType = BusinessType.DELETE)
    @PostMapping("/version/remove")
    @ResponseBody
    public AjaxResult removeVersion(String ids)
    {
        String[] idArray = StringUtils.split(ids, ",");
        Long[] versionIds = new Long[idArray.length];
        for (int i = 0; i < idArray.length; i++) {
            versionIds[i] = Long.valueOf(idArray[i]);
        }
        return toAjax(datasetService.deleteDatasetVersionByIds(versionIds));
    }

    /**
     * 比较版本差异
     */
    @ApiOperation("比较版本差异")
    @PostMapping("/version/compare")
    @ResponseBody
    public AjaxResult compareVersions(Long versionId1, Long versionId2)
    {
        try
        {
            Map<String, Object> result = datasetService.compareVersions(versionId1, versionId2);
            return AjaxResult.success(result);
        }
        catch (Exception e)
        {
            return AjaxResult.error("比较版本失败: " + e.getMessage());
        }
    }

    /**
     * 获取数据集详情
     */
    @ApiOperation("获取数据集详情")
    @GetMapping("/info/{datasetId}")
    @ResponseBody
    public AjaxResult getDatasetInfo(@PathVariable("datasetId") Long datasetId)
    {
        SysDataset dataset = datasetService.selectDatasetById(datasetId);
        if (dataset == null)
        {
            return AjaxResult.error("数据集不存在");
        }
        return AjaxResult.success(dataset);
    }
}